﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Security.Principal;
using System.Runtime.Serialization;
using Parichay.Domain.Models;
using Parichay.Domain.Interface.Data;

namespace Parichay.MVC.Controllers
{
    public class BaseController : Controller
    {
        //
        // GET: /Base/
                // Using StructureMap Dependency Injection Container
        // The mappings can be found in Parichay.Common.Util.Bootstrapper.Run()
        protected IMemberRepository _memberRepository;
        protected ILogRepository _logRepository;

        public BaseController(IMemberRepository memberRepository,ILogRepository logRepository)
        {
            this._memberRepository = memberRepository;
            this._logRepository = logRepository;
        }

        public BaseController()
            : this(StructureMap.ObjectFactory.GetInstance<IMemberRepository>(), StructureMap.ObjectFactory.GetInstance<ILogRepository>())
        {
        }
        /// <summary>
        /// Gets a value indicating whether the currently visiting user is authenticated.
        /// </summary>
        /// <value>
        /// if user authenticated returns <c>true</c>; otherwise, <c>false</c>.
        /// </value>
        protected bool IsUserAuthenticated
        {
            //[DebuggerStepThrough]
            get { return HttpContext.User.Identity.IsAuthenticated; }
        }


        /// <summary>
        /// Gets the Complete IP address of current user. If the user is not authenticated it returns "Anonymous"
        /// </summary>
        /// <value>IP address of the current user.</value>
        protected string LoggedInUserIp
        {
            get
            {
                string ipstr = "";
                for (int tmp1 = 0; tmp1 <= System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()).Length - 1; tmp1++)
                {
                    ipstr += System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()).GetValue(tmp1).ToString() + " | ";
                }
                return (ipstr.TrimEnd(new char[] { '|', ' ' }));
            }
        }

        /// <summary>
        /// Gets the Membership User Key for the current user. If the user is not authenticated it returns "Anonymous"
        /// </summary>
        /// <value>The Membership UserKey of the current user.</value>
        protected int LoggedInUserKey
        {
            //[DebuggerStepThrough]
            get
            {

                int rtRn = 0;

                if (IsUserAuthenticated)
                {
                    rtRn = ((CustomIdentity)HttpContext.User.Identity).UserKey;

                    if (rtRn == 0)
                    { rtRn = Int32.Parse(Membership.GetUser(HttpContext.User.Identity.Name).ProviderUserKey.ToString()); }
                }

                return rtRn;
            }

        }

        /// <summary>
        /// Gets the name of the current user. If the user is not authenticated it returns "Anonymous"
        /// </summary>
        /// <value>The name of the current user.</value>
        protected string LoggedInUserName
        {
            //[DebuggerStepThrough]
            get
            {
                string rtRn = string.Empty;

                if (IsUserAuthenticated)
                {
                    rtRn = ((CustomIdentity)HttpContext.User.Identity).Name;

                    if (string.IsNullOrEmpty(rtRn.Trim()))
                    { rtRn = Membership.GetUser(HttpContext.User.Identity.Name).UserName; }
                }

                return rtRn;
            }
        }


        /// <summary>
        /// Gets the email of the current user. If the user is not authenticated it returns empty string.
        /// </summary>
        /// <value>The email of the current user.</value>
        protected string LoggedInUserEmail
        {
            //get { return IsUserAuthenticated ? Membership.GetUser(LoggedInUserName, true).Email : string.Empty; }
            get
            {
                string rtRn = string.Empty;

                if (IsUserAuthenticated)
                {
                    rtRn = ((CustomIdentity)HttpContext.User.Identity).Email;

                    if (string.IsNullOrEmpty(rtRn.Trim()))
                    { rtRn = Membership.GetUser(HttpContext.User.Identity.Name).Email; }
                }

                return rtRn;
            }
        }


        protected bool IsJsonRequest()
        {
            string requestedWith = Request.ServerVariables["HTTP_X_REQUESTED_WITH"] ?? string.Empty;
            return string.Compare(requestedWith, "XMLHttpRequest", true) == 0
                && Request.ContentType.ToLower().Contains("application/json");
        }

        protected void SendMail(string to, string subject, string body)
        {
            try
            {
                //********Remember to comment out SpecifiedPickupDirectory settings in Helpers.Email class once you configure your mail client********//

                Email ml = new Email(AppConstants.adminEmail, to, subject, body, false);
                ml.send();
                _logRepository.Log("Email Sent=> " + ml.ToString(), Domain.LogType.Warn);
            }
            catch (Exception ex)
            {
                //throw;
                _logRepository.Log(new Exception("Error Sending Mail to:" + to.ToString(), ex));
            }

        }


        protected void Alert(int to, string message)
        {
            try
            {
                Domain.MemberAlert obj = new Domain.MemberAlert();
                obj.Ishidden = 0;
                obj.Message = message;
                obj.PUser = _memberRepository.getUserById(to);
                //obj.AlertType = new Alerttype() {Id=0 };
                Data.Helper.NHibernateHelper.Save<Domain.MemberAlert>(obj);
                TempData["message"] = "Requested User Notified.";

            }
            catch (Exception ex1)
            {
                _logRepository.Log(new Exception("Error Notifying UserKey:" + to.ToString(), ex1));
                TempData["message"] = "Unable to Notify. Error: " + ex1.Message;

            }
        }

        public bool HasPermission(string controllerName, string actionName)
        {
            bool _HasUserPermission = false,_HasPermission=false;
            int id = LoggedInUserKey;
            string[] currentUserRoles= Roles.GetRolesForUser();
            string[] rolesForAction= Parichay.Security.ADHSecurityHelper.GetRolesForControllerAction(LoggedInUserKey.ToString(), out _HasUserPermission, controllerName, actionName);

            //Has a user level permission to this action
            if (_HasUserPermission)
            {
                _HasPermission = true;
            }
            else if (((rolesForAction != null) && (rolesForAction.Length > 0)) 
                && ((currentUserRoles != null) && (currentUserRoles.Length > 0)) 
                && (rolesForAction.Any(currentUserRoles.Contains)))//Check for role level access
            {
                    _HasPermission = true;
            }
            return _HasPermission;
        }

        #region Messaging helpers
        protected int[] getFriendIds(int userId)
        {
            return (_memberRepository.getFriendIds(userId));
        }

        protected IList<Domain.MemberAlert> getAlertsByUId(int uId)
        {
            IList<Domain.MemberAlert> objList = Data.Helper.NHibernateHelper.ConvertToListOf<Domain.MemberAlert>(Data.Helper.NHibernateHelper.Find("select distinct a from MemberAlert a where a.PUser.Id = ? and a.Ishidden = ? order by Version desc", new object[] { uId, 0 }, new NHibernate.Type.IType[] { NHibernate.NHibernateUtil.Int32, NHibernate.NHibernateUtil.Int32 }, false));
            return (objList);
        }

        protected IList<Domain.MemberRequests> getRequestsByUId(int uId)
        {
            IList<Domain.MemberRequests> myRequests = Data.Helper.NHibernateHelper.ConvertToListOf<Domain.MemberRequests>(Data.Helper.NHibernateHelper.Find("select distinct a from MemberRequests a where a.Senderid = ? or a.Recipientid.Id = ? order by Version desc", new object[] { uId, uId }, new NHibernate.Type.IType[] { NHibernate.NHibernateUtil.Int32, NHibernate.NHibernateUtil.Int32 }, false));
            return myRequests;
        }
        protected IList<Domain.MemberInvitations> getInvitesByUIdOrEmail(int uId, string usrEmail)
        {
            IList<Domain.MemberInvitations> myInvites = Data.Helper.NHibernateHelper.ConvertToListOf<Domain.MemberInvitations>(Data.Helper.NHibernateHelper.Find("select distinct a from MemberInvitations a where a.Senderid = ? or a.Email = ? order by Version desc", new object[] { uId, usrEmail }, new NHibernate.Type.IType[] { NHibernate.NHibernateUtil.Int32, NHibernate.NHibernateUtil.String }, false));
            return myInvites;
        }
        #endregion Messaging helpers
    }
}